<?php 
/**
* 验证码类
*/
class Code
{
	public $config = array(
		'width'=>150,
		'height'=>80,
		'fontsize'=>30,
		'lenght'=>4,
		'jam'=>false,
		'gbcolor'=>[255,255,255],
		'str'=>'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890'
		);

	public $src;
	
	public function __construct($config=array())
	{
		$this->config = array_merge($this->config,$config);
	}

	public function show()
	{
		$this->createCanvas();
		$this->createJams();
		$this->createText();
		$this->outPut();
	}

	public function __get($key)
	{
		return $this->config[$key];
	}

	public function createCanvas()
	{
		$this->src = imageCreateTrueColor($this->width,$this->height); 

		//选颜色
		$color = imageColorAllocate($this->src,$this->gbcolor[0],$this->gbcolor[1],$this->gbcolor[2]); 
		//填充
		imageFill($this->src,0,0,$color);
	}

	public function createJams()
	{
		if($this->jam){
			for ($i=0; $i <20 ; $i++) { 

				$color = imageColorAllocate($this->src,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));

				$word = $this->str[mt_rand(0,strlen($this->str)-1)];

				imagettftext ( $this->src, 15,mt_rand(-30,30) , mt_rand(0,$this->width), mt_rand(0,$this->height) ,$color , './kingthings Hand.ttf' , $word);
			}
		}
	}

	public function createText()
	{

		$color = imageColorAllocate($this->src,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));

		$height = ($this->height+$this->fontsize)/2;

		$width = (($this->width/$this->lenght)-$this->fontsize)/2;

		for ($i=0; $i < $this->lenght ; $i++) { 

			$word = $this->str[mt_rand(0,strlen($this->str)-1)];


			imagettftext ( $this->src,$this->fontsize,mt_rand(-15,15) ,$width ,$height,$color , './kingthings Hand.ttf' , $word);

			$width +=($this->width/$this->lenght);
		}
	}

	public function outPut()
	{

		header("Content-type: image/png");
		//输出
		imagepng($this->src);  
		//销毁
		imageDestroy($this->src);
	}
}









 ?>